package com.thread.prodcustrom;

import java.util.concurrent.Semaphore;

public class TestSemaphoreConsumerAndProducer {
	/*当前生成数量*/
	static int currentNum = 0;
	/*最大生成数量*/
	static int MAX_NUM = 10;
	/*最小消费数量*/
	static int MIN_NUM = 1;

	static Semaphore mutexProduct = new Semaphore(10);
	static Semaphore mutexCustromer = new Semaphore(0);
	static Semaphore mutex = new Semaphore(1);

	public static void main(String args[]) {
		//创建一个生产者
		new Thread(new Producer()).start();

//		//创建两个消费者
//		new Thread(new Consumer()).start();
//		new Thread(new Consumer()).start();
	}


	static class Producer implements Runnable {
		public void product() {
			while (true) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				try {
					mutexProduct.acquire();
					mutex.acquire();
					currentNum++;
					System.out.println(new StringBuilder(Thread.currentThread().getName())
							.append(" Producer now product num:").append(currentNum));

					if(currentNum==9){
						mutexProduct.release();
					}
					mutex.release();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}

		@Override
		public void run() {
			product();
		}
	}

	static class Consumer implements Runnable {
		public void consume() {
			while (true) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				try {
					mutexCustromer.acquire();
					mutex.acquire();
				} catch (InterruptedException e) {
				}

				--currentNum;
				System.out.println(new StringBuilder(Thread.currentThread().getName())
						.append(" Consumer now consumption num:").append(currentNum));
				if(currentNum>=MIN_NUM){
					mutex.release();
					mutexProduct.release();
					continue;
				}
				mutexCustromer.release();
			}
		}

		@Override
		public void run() {
			consume();
		}
	}
}
